<template>
  <div class="flex-container">
    <div class="form-wrapper">
      <el-form ref="formRef" :model="formData" :rules="rules">
        <el-form-item label="所属购买企业" prop="corpId">
          <el-select
            v-model="formData.corpId"
            placeholder="请选择企业信息"
            style="width: 240px"
            clearable
          >
            <el-option
              v-for="e in myCpInfos"
              :key="e.corpId"
              :value="e.corpId"
              :label="e.corpName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="选择账号数量" prop="htNum">
          <el-select v-model="formData.htNum" placeholder="请选择数量" :disabled="submitFormStatus">
            <el-option
              v-for="(item, index) in htNumValues"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择购买时长" prop="buyId">
          <el-select v-model="formData.buyId" placeholder="请选择时长" :disabled="submitFormStatus">
            <el-option
              v-for="(item, index) in buyMonthsValues"
              :key="index"
              :label="item.title"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 总价显示 -->
        <el-form-item label="总价">
          <span class="total-price">¥ {{ totalPrice() }}</span>
        </el-form-item>
      </el-form>
      <div v-if="!submitFormStatus">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">立即发起微信支付</el-button>
      </div>
      <div v-if="qrCodeValue">
        <QrcodeVue :value="qrCodeValue" :size="200" level="H" />
        <br/>
        <span>请使用微信扫码支付</span>
      </div>
    </div>
  </div>
</template>

<script setup name="JqtCpHtUserBuy" lang="ts">
import { getBuyMonths, getOrderPayStatus, payHtAccount } from '@/api/bus/jqtCpHtOrder';
import { JqtCpHtBuyMonthsVo } from '@/api/bus/jqtCpHtOrder/types';
import QrcodeVue from 'qrcode.vue'
import { JqtCpHtInfoVO } from '@/api/bus/jqtCpHtInfo/types';
import { getCpList } from '@/api/bus/jqtCpHtInfo';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable,bus_ht_user_type } = toRefs<any>(proxy?.useDict('sys_normal_disable','bus_ht_user_type'));

const buttonLoading = ref(false);
const formRef = ref<ElFormInstance>();
export interface JqtCpHtUserBuyForm {
  // 所属企业id
  corpId:number|string;
  // 购买数量
  htNum:number;
  // 购买商品id
  buyId:number;
}
const initFormData: JqtCpHtUserBuyForm = {
  corpId: undefined,
  htNum: 1,
  buyId: undefined
}
const formData = reactive<JqtCpHtUserBuyForm>({
  ...initFormData
});

const rules = {
  corpId: [
    { required: true, message: "所属企业不能为空", trigger: "change" }
  ],
  htNum: [
    { required: true, message: "购买互通账号数量不能为空", trigger: "blur" }
  ],
  buyId: [
    { required: true, message: "购买时长不能为空", trigger: "change" }
  ]
}
onMounted(async () => {
  await getMyCpInfoData();
  setHtNumValues();
  await setBuyMonthsValues();
});
// 购买互通账号数量
const htNumValues = []
const setHtNumValues = () => {
  for (let i = 1; i <= 10; i++) {
    htNumValues.push({
      label: i + '个',
      value: i
    })
  }
}
const buyMonthsValues = ref<JqtCpHtBuyMonthsVo[]>();
const setBuyMonthsValues = async () => {
  const res = await getBuyMonths()
  buyMonthsValues.value = res.data
}

// 实时计算总价
const totalPrice = () =>  {
  const { htNum, buyId } = formData

  // 如果任一未选择，返回 0
  if (!htNum || !buyId) return 0

  // 查找对应时长的单价
  const selected = buyMonthsValues.value.find(item => item.id === buyId)
  if (!selected) return 0
  // 数量 × 单价
  return selected.price * htNum
}
// 二维码值
const qrCodeValue = ref('');
// 支付交易号
const serialNumber = ref('');
// 提交表单状态
const submitFormStatus = ref<boolean>(false);
/** 提交按钮 */
const submitForm = () => {
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      const res = await payHtAccount(formData).finally(() =>  buttonLoading.value = false);
      qrCodeValue.value = res.data.codeUrl;
      serialNumber.value = res.data.serialNumber;
      submitFormStatus.value = true;
    }
  });
}
/** 轮询订单支付状态 */
const getOrderPayStatusInfo = async () => {
  const res = await getOrderPayStatus(serialNumber.value);
  return res.data;
};

const myCpInfos = ref<JqtCpHtInfoVO[]>([]);
/**
 * 获取企业信息
 */
const getMyCpInfoData = async () => {
  const res = await getCpList();
  myCpInfos.value = res.data;
};
// 暴露给父组件调用的方法
defineExpose({
  getOrderPayStatusInfo,
})
</script>

<style scoped>
.flex-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 60vh;
}

.form-wrapper {
  width: 1000px;
  padding: 20px;
  border: 1px solid #dcdfe6; /* 标准边框，颜色与 Element Plus 风格一致 */
  border-radius: 8px;        /* 圆角，更美观 */
  background-color: #ffffff; /* 白色背景 */
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); /* 可选：添加阴影，提升层次感 */
}

.total-price {
  font-size: 18px;
  font-weight: bold;
  color: #f50;
}
</style>
